package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sky.constant.StatusConstant;
import com.sky.entity.Setmeal;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;

@RestController("userSetmealController")
@RequestMapping("/user/setmeal")
@Api(tags = "C端-套餐浏览接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //创建redis的key
    public static final String KEY = "Setmeal_";

    /**
     * 条件查询
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询套餐")
    public Result<List<Setmeal>> list(Long categoryId) {

        //获取redis中的菜品
        String s = redisTemplate.opsForValue().get(KEY+categoryId);
        List<Setmeal> setmealList = JSONArray.parseArray(s,Setmeal.class);

        //判断该菜品是否存在，若存在，则直接返回
        if (setmealList != null && setmealList.size() > 0) {
            return Result.success(setmealList);
        }

        Setmeal setmeal = new Setmeal();
        setmeal.setCategoryId(categoryId);
        setmeal.setStatus(StatusConstant.ENABLE);

         setmealList = setmealService.list(setmeal);

        //再缓存到redis
        redisTemplate.opsForValue().set(KEY+categoryId, JSON.toJSONString(setmealList));
        return Result.success(setmealList );
    }

    /**
     * 根据套餐id查询包含的菜品列表
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    @ApiOperation("根据套餐id查询包含的菜品列表")
    public Result<List<DishItemVO>> dishList(@PathVariable("id") Long id) {
        //获取redis中的菜品
        String s = redisTemplate.opsForValue().get(KEY+"dish_"+id);
        List<DishItemVO> dishItemVOList = JSONArray.parseArray(s,DishItemVO.class);

        //判断该菜品是否存在，若存在，则直接返回
        if (dishItemVOList != null && dishItemVOList.size() > 0) {
            return Result.success(dishItemVOList);
        }
        dishItemVOList = setmealService.getDishItemById(id);

        //再缓存到redis
        redisTemplate.opsForValue().set(KEY+"dish_"+id, JSON.toJSONString(dishItemVOList));
        return Result.success(dishItemVOList);
    }
}
